package cn.edu.neusoft.amicooldemo;

import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.menu.ActionMenuItemView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import org.w3c.dom.Text;

import cn.edu.neusoft.amicooldemo.bean.Constants;
import cn.edu.neusoft.amicooldemo.bean.VideoBean;
import cn.edu.neusoft.amicooldemo.factory.AmicoolFactory;
import cn.edu.neusoft.amicooldemo.iface.CollectListener;
import cn.edu.neusoft.amicooldemo.iface.FocusListener;
import cn.edu.neusoft.amicooldemo.mclass.CustomVideoView;
import cn.edu.neusoft.amicooldemo.mclass.DensityUtils;
import cn.edu.neusoft.amicooldemo.model.CollectModel;
import cn.edu.neusoft.amicooldemo.model.FocusModel;

public class ViewvideoActivity extends AppCompatActivity implements View.OnClickListener, CollectListener, FocusListener {
    private static final String TAG = "ViewvideoActivity";
    private String url;
    /**
     * 视频相关变量
     */
    private CustomVideoView videoView;

    private LinearLayout controllerLayout;
    private ImageView play_controller_img;
    private TextView time_curren_tv;
    private TextView time_total_tv;
    private SeekBar play_seek, volume_seek;
    private ImageView screen_img;

    private static final int UPDATE_UI = 1;

    private int screen_width;
    private int screen_height;
    private RelativeLayout videoLayout;

    private AudioManager audioManager;
    private ImageView volumn_img;

    private boolean isFullScreen = false;

    private boolean isAdjust = false;
    private int threshold = 14;
    private float lastX = 0;
    private float lastY = 0;
    private float mBrightness;

    private ImageView operation_bg;
    private ImageView operation_percent;
    private FrameLayout progress_layout;

    private LinearLayout v_info_layout;
    private ImageView v_collect;
    private ImageView v_focus;
    private TextView v_name;
    private TextView v_time;
    private TextView v_author;
    private TextView v_description;
    /***
     * 数据相关变量
     */
    private int resid;
    private int idolid;
    private String SessionID;
    private SharedPreferences sp;
    private VideoBean bean;
    private int collect;
    private int focus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_viewvideo);

        init();
        setPlayerEvent();
        videoView.setVideoURI(Uri.parse(url));
        videoView.start();
        UIHandler.sendEmptyMessage(UPDATE_UI);

    }


    //格式化时间
    private void updateTextViewWithTimeFormat(TextView textView, int millisecond) {
        int second = millisecond / 1000;
        int hh = second / 3600;
        int mm = second % 3600 / 60;
        int ss = second % 60;
        String str = null;
        if (hh != 0) {
            str = String.format("%02d:%02d:%02d", hh, mm, ss);
        } else {
            str = String.format("%02d:%02d", mm, ss);
        }

        textView.setText(str);
    }

    private Handler UIHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == UPDATE_UI) {
                //获取视频当前播放时间以及视频播放总时间
                int currentPosition = videoView.getCurrentPosition();
                int totalduration = videoView.getDuration();

                updateTextViewWithTimeFormat(time_curren_tv, currentPosition);
                updateTextViewWithTimeFormat(time_total_tv, totalduration);
                play_seek.setMax(totalduration);
                play_seek.setProgress(currentPosition);
                //自调用
                UIHandler.sendEmptyMessageDelayed(UPDATE_UI, 500);
            }
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
        UIHandler.removeMessages(UPDATE_UI);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void setPlayerEvent() {
        //控制视频播放和暂停
        play_controller_img.setOnClickListener(this);

        //视频进度条拖动事件
        play_seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //同步时间
                updateTextViewWithTimeFormat(time_curren_tv, progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //刚开始拖动时停止UI
                UIHandler.removeMessages(UPDATE_UI);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //同步视频
                int progress = seekBar.getProgress();
                videoView.seekTo(progress);
                UIHandler.sendEmptyMessage(UPDATE_UI);
            }
        });

        //音量进度条拖动事件
        volume_seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                /**
                 * 设置当前系统音量
                 * */
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        //屏幕缩放事件
        screen_img.setOnClickListener(this);
        /**
         * 控制VideoView的手势事件
         * */
        videoView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                float x = event.getX();
                float y = event.getY();


                switch (event.getAction()) {
                    /**
                     * 手指落下屏幕时(只会调用一次)
                     * */
                    case MotionEvent.ACTION_DOWN: {
                        Log.d(TAG, "起始坐标：" + x + " " + y);
                        lastX = x;
                        lastY = y;

                        break;
                    }
                    /**
                     * 手指在屏幕上移动（调用多次）
                     * */
                    case MotionEvent.ACTION_MOVE: {
                        float detlaX = x - lastX;
                        float detlaY = y - lastY;
                        Log.d(TAG, "获取坐标：" + lastX + " " + lastY);
                        float absdetlaX = Math.abs(detlaX);
                        float absdetlaY = Math.abs(detlaY);
                        /**
                         * 手势合法性验证
                         * */
                        Log.d(TAG, "onTouch: " + "调用手势移动事件 :" + detlaY);
                        if (absdetlaX > threshold && absdetlaY > threshold) {
                            if (absdetlaX < absdetlaY) {
                                isAdjust = true;
                            } else {
                                isAdjust = false;
                            }
                        } else if (absdetlaX < threshold && absdetlaY > threshold) {
                            isAdjust = true;
                        } else if (absdetlaX > threshold && absdetlaY < threshold) {
                            isAdjust = false;
                        }
                        Log.d(TAG, "onTouch: " + "手势是否合法" + isAdjust);
                        if (isAdjust) {
                            /**
                             * 在判断好当前手势事件已经合法的情况下，去区分此时手势应该是调节亮度还是调节声音
                             * */
                            if (x < screen_width / 2) {
                                //调节亮度
                                if (detlaY > 0) {
                                    //降低亮度
                                } else {
                                    //升高亮度
                                }
                                changeBrightness(detlaY);
                            } else {
                                //调节声音
                                if (detlaY > 0) {
                                    //减小声音
                                } else {
                                    //增大音量
                                }
                                changeVolume(-detlaY);

                            }
                        }


                        break;
                    }
                    /**
                     * 手指离开屏幕时
                     * */
                    case MotionEvent.ACTION_UP: {
                        Log.d(TAG, "onTouch: 手离开");
                        progress_layout.setVisibility(View.GONE);
                        break;
                    }
                }
                return true;
            }
        });
    }

    private void changeVolume(float detlaY) {
        int max = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        int current = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        int index = (int) (detlaY / screen_height * max / 4);
        int volume = Math.max(current + index, 0);
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);
        volume_seek.setProgress(volume);
        if (progress_layout.getVisibility() == View.GONE) {
            progress_layout.setVisibility(View.VISIBLE);
        }
        operation_bg.setImageResource(R.drawable.video_volumn_bg);
        ViewGroup.LayoutParams layoutParams = operation_percent.getLayoutParams();
        layoutParams.width = (int) (DensityUtils.dip2px(this, 94) * (float) volume / max);
        operation_percent.setLayoutParams(layoutParams);
        progress_layout.setVisibility(View.VISIBLE);
        Log.d(TAG, "changeVolume: 增加的音量" + detlaY);
    }

    private void changeBrightness(float detlaY) {
        WindowManager.LayoutParams attributes = getWindow().getAttributes();
        mBrightness = attributes.screenBrightness;
        float index = detlaY / screen_height / 3;
        mBrightness += index;
        if (mBrightness > 1.0f) {
            mBrightness = 1.0f;
        }
        if (mBrightness < 0.01f) {
            mBrightness = 0.01f;
        }
        Log.d(TAG, "changeBrightness: 亮度为 " + mBrightness);
        attributes.screenBrightness = mBrightness;
        if (progress_layout.getVisibility() == View.GONE) {
            progress_layout.setVisibility(View.VISIBLE);
        }
        operation_bg.setImageResource(R.drawable.video_brightness_bg);
        ViewGroup.LayoutParams layoutParams = operation_percent.getLayoutParams();
        layoutParams.width = (int) (DensityUtils.dip2px(this, 94) * mBrightness);
        operation_percent.setLayoutParams(layoutParams);
        progress_layout.setVisibility(View.VISIBLE);
        getWindow().setAttributes(attributes);
    }

    private void init() {
        /***
         * 数据相关
         */
        v_info_layout = (LinearLayout) findViewById(R.id.v_info_layout);
        v_collect = (ImageView) findViewById(R.id.v_collect_img);
        v_focus = (ImageView) findViewById(R.id.v_focus_img);
        v_collect.setOnClickListener(this);
        v_focus.setOnClickListener(this);
        focus = 0;
        collect = 0;
        resid = getIntent().getIntExtra("resid", 1);
        idolid = getIntent().getIntExtra("userid", 7);
        bean = (VideoBean) getIntent().getSerializableExtra("bean");
        sp = getSharedPreferences("amicool_user", MODE_PRIVATE);
        SessionID = sp.getString("SessionID", "dfrcg3211kjb1vbe3ibgftkfa6");
        url = Constants.SERVERADDRESS + "Uploads/video/video/" + bean.getVideopath();

        CollectModel.getInstance().exists("video", resid, SessionID, this);
        FocusModel.getInstance().exists("userfocus", idolid, SessionID, this);

        v_name = (TextView)findViewById(R.id.v_name);
        v_name.setText(getIntent().getStringExtra("vname"));
        v_time = (TextView)findViewById(R.id.v_time);
        v_time.setText(getIntent().getStringExtra("vtime"));
        v_author = (TextView)findViewById(R.id.v_author);
        v_author.setText(getIntent().getStringExtra("vauthor"));
        v_description = (TextView)findViewById(R.id.v_description);
        v_description.setText(bean.getDescription());
        /**
         * 视频相关
         */
        videoView = (CustomVideoView) findViewById(R.id.videoView);
        controllerLayout = (LinearLayout) findViewById(R.id.controllerbar_layout);
        play_controller_img = (ImageView) findViewById(R.id.pause_img);
        screen_img = (ImageView) findViewById(R.id.screen_img);
        time_curren_tv = (TextView) findViewById(R.id.time_current_tv);
        time_total_tv = (TextView) findViewById(R.id.time_total_tv);
        volume_seek = (SeekBar) findViewById(R.id.volume_seek);
        play_seek = (SeekBar) findViewById(R.id.play_seek);

        screen_width = getResources().getDisplayMetrics().widthPixels;
        screen_height = getResources().getDisplayMetrics().heightPixels;
        videoLayout = (RelativeLayout) findViewById(R.id.videoLayout);
        //获取系统音频服务
        audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        //当前设备最大音量
        int streamMaxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        //当前设备音量
        int streamVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        volume_seek.setMax(streamMaxVolume);
        volume_seek.setProgress(streamVolume);
        volumn_img = (ImageView) findViewById(R.id.volume_img);

        operation_bg = (ImageView) findViewById(R.id.operation_bg);
        operation_percent = (ImageView) findViewById(R.id.operation_percent);
        progress_layout = (FrameLayout) findViewById(R.id.progress_layout);

    }

    private void setVideoViewStyle(int width, int height) {
        ViewGroup.LayoutParams layoutParams = videoView.getLayoutParams();
        layoutParams.width = width;
        layoutParams.height = height;
        videoView.setLayoutParams(layoutParams);

        ViewGroup.LayoutParams layoutParams1 = videoLayout.getLayoutParams();
        layoutParams1.width = width;
        layoutParams1.height = height;
        videoLayout.setLayoutParams(layoutParams);
    }

    /**
     * 监听到屏幕方向的改变
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        /**
         * 屏幕方向横屏
         * */
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            setVideoViewStyle(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            volumn_img.setVisibility(View.VISIBLE);
            volume_seek.setVisibility(View.VISIBLE);
            v_info_layout.setVisibility(View.GONE);
            isFullScreen = true;
            //移除半屏状态
            getWindow().clearFlags((WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN));
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

        }
        /**
         * 竖屏
         * */
        else {
            setVideoViewStyle(ViewGroup.LayoutParams.MATCH_PARENT, DensityUtils.dip2px(this, 290));
            volumn_img.setVisibility(View.GONE);
            volume_seek.setVisibility(View.GONE);
            v_info_layout.setVisibility(View.VISIBLE);
            isFullScreen = false;
            getWindow().clearFlags((WindowManager.LayoutParams.FLAG_FULLSCREEN));
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.pause_img:
                if (videoView.isPlaying()) {
                    play_controller_img.setImageResource(R.drawable.play_btn_style);
                    videoView.pause();
                    //UI与视频播放与否同步
                    UIHandler.removeMessages(UPDATE_UI);
                } else {
                    play_controller_img.setImageResource(R.drawable.pause_btn_style);
                    videoView.start();
                    UIHandler.sendEmptyMessage(UPDATE_UI);
                }
                break;

            case R.id.screen_img:
                if (isFullScreen) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                } else {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }
                break;

            case R.id.v_collect_img:
                if (collect == 0) {

                    CollectModel.getInstance().collect("video", resid, SessionID, this);
                } else {
                    CollectModel.getInstance().uncollect("video", resid, SessionID, this);
                }
                break;

            case R.id.v_focus_img:
                if (focus == 0) {
                    FocusModel.getInstance().focus("userfocus", idolid, SessionID, this);
                }
               /* else{
                    FocusModel.getInstance().unfocus("userfocus",idolid,SessionID,this);
                }*/
                break;
        }
    }

    @Override
    public void onResponse(String msg) {
        switch (msg) {
            case "1":
                //判断是否已收藏
                collect = 0;
                v_collect.setImageResource(R.drawable.v_collect_grey);
                break;
            case "3":
                //收藏返回处理
                collect = 1;
                v_collect.setImageResource(R.drawable.v_collect_yellow);
                break;
            default:
                //取消收藏返回处理
                collect = 0;
                v_collect.setImageResource(R.drawable.v_collect_grey);
                break;
        }
    }

    @Override
    public void onFail(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onFocusResponse(String msg) {
        switch (msg) {
            case "1":
                //判断是否已收藏
                focus = 0;
                v_focus.setImageResource(R.drawable.v_focus_gray);
                break;
            case "3":
                //收藏返回处理
                focus = 1;
                v_focus.setImageResource(R.drawable.v_focus_yellow);
                break;
            default:
                //取消收藏返回处理
                focus = 0;
                v_focus.setImageResource(R.drawable.v_focus_gray);
                break;
        }
    }

    @Override
    public void onFocusFail(String msg) {

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }
}
